<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="钱包地址" prop="walletAddress">
              <el-input v-model="queryParams.walletAddress" placeholder="请输入钱包地址" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="质押产品" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入质押产品" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="质押时间" prop="dateRange">
              <el-date-picker
                v-model="queryParams.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :shortcuts="shortcuts"
                :clearable="true"
              />
            </el-form-item>
            <el-form-item label="最后返利日期" prop="lastRebateDateRange" label-width="120">
              <el-date-picker
                v-model="queryParams.lastRebateDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :shortcuts="shortcuts"
                :clearable="true"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable >
                <el-option v-for="dict in user_stakings_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <el-form
        class="-mb-15px"
        :inline="true"
        label-width="100px"
      >
        <el-form-item label="发放日期">
          <el-date-picker v-model="dateTime" type="date" value-format="YYYY-MM-DD" format="YYYY-MM-DD" placeholder="选择日期"/>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            plain
            @click="fafang()"
            v-hasPermi="['business:userProduct:distribute']"
          >
            收益发放
          </el-button>
        </el-form-item>
      </el-form>

    </el-card>

    <el-card shadow="never">
      <el-table v-loading="loading" border :data="userStakingsList" @selection-change="handleSelectionChange">
        <el-table-column label="订单号" align="center" prop="orderNo" />
        <el-table-column label="质押产品" align="center" prop="productName" />
        <el-table-column label="钱包地址" align="center" prop="walletAddress" width="260" />
        <el-table-column label="质押金额(USDZ)" align="center" prop="stakingAmount" />
        <el-table-column label="日收益率(%)" align="center" prop="dailyRate" />
        <el-table-column label="质押周期(天)" align="center" prop="periodDays" />
        <el-table-column label="预计总收益(USDZ)" align="center" prop="totalEarnings" />
        <el-table-column label="已支付收益(USDZ)" align="center" prop="paidEarnings" />
        <el-table-column label="剩余天数(天)" align="center" prop="remainingDays" />
        <el-table-column label="质押时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收益开始日期" align="center" prop="startDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收益结束日期" align="center" prop="endDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最后返利日期" align="center" prop="lastRebateDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.lastRebateDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="user_stakings_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
<!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--          <template #default="scope">-->
<!--            <el-tooltip content="修改" placement="top">-->
<!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:userStakings:edit']"></el-button>-->
<!--            </el-tooltip>-->
<!--            <el-tooltip content="删除" placement="top">-->
<!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:userStakings:remove']"></el-button>-->
<!--            </el-tooltip>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改用户质押记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="userStakingsFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="产品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入产品ID" />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="质押金额" prop="stakingAmount">
          <el-input v-model="form.stakingAmount" placeholder="请输入质押金额" />
        </el-form-item>
        <el-form-item label="日收益率" prop="dailyRate">
          <el-input v-model="form.dailyRate" placeholder="请输入日收益率" />
        </el-form-item>
        <el-form-item label="质押周期" prop="periodDays">
          <el-input v-model="form.periodDays" placeholder="请输入质押周期" />
        </el-form-item>
        <el-form-item label="预计总收益" prop="totalEarnings">
          <el-input v-model="form.totalEarnings" placeholder="请输入预计总收益" />
        </el-form-item>
        <el-form-item label="已支付收益" prop="paidEarnings">
          <el-input v-model="form.paidEarnings" placeholder="请输入已支付收益" />
        </el-form-item>
        <el-form-item label="剩余天数" prop="remainingDays">
          <el-input v-model="form.remainingDays" placeholder="请输入剩余天数" />
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="最后返利日期" prop="lastRebateDate">
          <el-date-picker clearable
            v-model="form.lastRebateDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择最后返利日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in user_stakings_status"
              :key="dict.value"
              :value="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserStakings" lang="ts">
import { listUserStakings, getUserStakings, delUserStakings, addUserStakings, updateUserStakings, processRebates } from '@/api/business/userStakings';
import { UserStakingsVO, UserStakingsQuery, UserStakingsForm } from '@/api/business/userStakings/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { user_stakings_status } = toRefs<any>(proxy?.useDict('user_stakings_status'));

const userStakingsList = ref<UserStakingsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const userStakingsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: UserStakingsForm = {
  id: undefined,
  userId: undefined,
  productId: undefined,
  orderNo: undefined,
  stakingAmount: undefined,
  dailyRate: undefined,
  periodDays: undefined,
  totalEarnings: undefined,
  paidEarnings: undefined,
  remainingDays: undefined,
  startDate: undefined,
  endDate: undefined,
  lastRebateDate: undefined,
  status: undefined,
  walletAddress: undefined,
  productName: undefined,
  dateRange: [], // [startDate, endDate]
  lastRebateDateRange: [], // [startDate, endDate]
}
const data = reactive<PageData<UserStakingsForm, UserStakingsQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    productId: undefined,
    orderNo: undefined,
    stakingAmount: undefined,
    dailyRate: undefined,
    periodDays: undefined,
    totalEarnings: undefined,
    paidEarnings: undefined,
    remainingDays: undefined,
    startDate: undefined,
    endDate: undefined,
    lastRebateDate: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    paidEarnings: [
      { required: true, message: "已支付收益不能为空", trigger: "blur" }
    ],
    lastRebateDate: [
      { required: true, message: "最后返利日期不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
});
const dateTime = ref('');
const fafang = async ()=>{
  if(!dateTime.value){
    proxy?.$modal.msgError('请选择发放日期');
    return;
  }
  await processRebates(dateTime.value)
    proxy?.$modal.msgSuccess('发放成功');
    // 刷新列表
    await getList()
}

// 时间快捷选项（只包含日期）
const shortcuts = [
  {
    text: '今天',
    value: () => {
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  },
  {
    text: '昨天',
    value: () => {
      const start = new Date();
      start.setDate(start.getDate() - 1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setDate(end.getDate() - 1);
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date();
      end.setHours(23, 59, 59, 999);
      const start = new Date();
      start.setDate(start.getDate() - 6);
      start.setHours(0, 0, 0, 0);
      return [start, end];
    }
  },
  {
    text: '最近30天',
    value: () => {
      const end = new Date();
      end.setHours(23, 59, 59, 999);
      const start = new Date();
      start.setDate(start.getDate() - 29);
      start.setHours(0, 0, 0, 0);
      return [start, end];
    }
  },
  {
    text: '本月',
    value: () => {
      const start = new Date();
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  },
  {
    text: '上个月',
    value: () => {
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setMonth(end.getMonth() - 1);
      end.setDate(0);
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  }
];
const { queryParams, form, rules } = toRefs(data);

/** 查询用户质押记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listUserStakings(queryParams.value);
  userStakingsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  userStakingsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserStakingsVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加用户质押记录";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: UserStakingsVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getUserStakings(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改用户质押记录";
}

/** 提交按钮 */
const submitForm = () => {
  userStakingsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateUserStakings(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addUserStakings(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: UserStakingsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除用户质押记录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delUserStakings(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('business/userStakings/export', {
    ...queryParams.value
  }, `userStakings_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
